// userPageB/pages/userStore/cardPayNew/cardPayNew.js
const app = getApp()
const WXAPI = require("../../../../api/api")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nvabarData: {
      showCapsule: 1, // 是否显示左上角图标   1表示显示    0表示不显示
      title: '确认支付', // 导航栏 中间的标题
      textColor: '#333333', // 标题颜色
      bgColor: '#ffffff', // 导航栏背景颜色
      isColor: true,
      isloading: false,
    },
    // 此页面 页面内容距最顶部的距离
    imgHttp: app.globalData.imgHttp,
    assetId: '',
    referrerId: '',
    merchantId: '',
    cardData: {},
    documentUrl: '',
    isImg: true, //是否签署合约(小于等于500)
    isImgTwo: false, //是否签署合约(大于500)
    isRealName: false, //是否实名
    isContract: true, //是否阅读保险合约
    isInsurance: '', //是否参保 1 参保、 2 不参保、 3 参保卡大于5张
    signUrl: '', //签约合同地址
    signatureImg: '', //签名图片
    tipShow: false,//签约保险说明弹窗
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var assetId = options.assetId
    var merchantId = options.merchantId

    var referrerId = options.referrerId ? options.referrerId : ''
    var staffId = options.staffId ? options.staffId : ''
    this.setData({
      assetId: assetId,
      referrerId: referrerId,
      merchantId: merchantId,
      staffId: staffId
    })
    // this.getDetail()
    // setTimeout(() => { //(在卡优优2.4.1版本产品验收中屏蔽此功能2024-10-22)
    //   let isInsurance = wx.getStorageSync('isInsurance')
    //   if (isInsurance == 3) { //isInsurance = 3 就是超过5张
    //     this.showModalTwo()
    //   }
    // }, 1000)
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // wx.removeStorageSync('signInfo')
    let signInfo = wx.getStorageSync('signInfo')
    if (signInfo != '') {
      this.setData({
        signUrl: signInfo.url,
        signatureImg: signInfo.img,
      })
    }
    this.getDetail()
  },
  //重新签名
  reSign() {
    if (!this.data.isImgTwo) {
      wx.showToast({
        title: '请点击我已仔细阅读',
        icon: 'none'
      })
      return
    }
    wx.navigateTo({
      url: '/userPageB/pages/userStore/electronicContract/signature/signature?assetId=' + this.data.assetId + '&merchantId=' + this.data.merchantId,
    })
  },
  //获取订单详情
  getDetail() {
    var data = {
      assetId: this.data.assetId,
      referrerId: this.data.referrerId,
      merchantId: this.data.merchantId,
      staffId: this.data.staffId
    }
    WXAPI.confirmOrder(data, (res) => {
      // console.log('订单确认页面', res)
      const {
        result
      } = res
      if (result.name != '') {
        this.setData({
          isRealName: true
        })
      }
      this.setData({
        cardData: result,
        isInsurance: result.isInsurance
      })
      // if (Number(this.data.cardData.buyMoney) > 500) {
      //   this.setData({
      //     isImg: false
      //   })
      // } else {
      //   this.setData({
      //     isImg: true
      //   })
      // }
      wx.setStorageSync('isInsurance', result.isInsurance)
    })
  },
  handleSel() { //点击确认并自动签署合同(小于等于500)
    this.setData({
      isImg: !this.data.isImg
    })
  },
  handleSelTwo() { //点击确认并自动签署合同(大于500)
    this.setData({
      isImgTwo: !this.data.isImgTwo
    })
  },
  clickIsContract() { //点击是否确认保险合约
    this.setData({
      isContract: !this.data.isContract
    })
  },
  //查看保险合约
  lookInsuranceContract(e) {
    console.log(e.currentTarget.dataset.contract)
    let insuranceContract = e.currentTarget.dataset.contract
    var url = this.data.imgHttp + insuranceContract
    var index = url.lastIndexOf("\.");
    var type = url.substring(index + 1, url.length);
    wx.showLoading({
      title: '加载中',
      mask: true,
    })
    wx.downloadFile({
      url: url,
      header: {},
      success: function (res) {
        var filePath = res.tempFilePath;
        console.log(filePath);
        wx.openDocument({
          filePath: filePath,
          fileType: type,
          success: function (res) {
            console.log('打开文档成功')
          },
          fail: function (res) {
            console.log("1111111111111", res);
          },
          complete: function (res) {
            console.log("22222222222222", res);
          }
        })
        wx.hideLoading()
      },
      fail: function (res) {
        console.log('文件下载失败');
        wx.hideLoading()
      },
      complete: function (res) {},
    })
  },
  //查看合同
  handleContract() {
    var data = {
      assetId: this.data.assetId,
      merchantId: this.data.merchantId
    }
    WXAPI.contractInfo(data, (res) => {
      // console.log('合同', res)
      const {
        result
      } = res
      this.setData({
        documentUrl: result
      })
      this.lookContract()
    })
  },

  //查看合同
  lookContract() {
    var url = this.data.imgHttp + this.data.documentUrl
    console.log(url)
    var index = url.lastIndexOf("\.");
    var type = url.substring(index + 1, url.length);
    wx.showLoading({
      title: '加载中',
      mask: true,
    })
    wx.downloadFile({
      url: url,
      header: {},
      success: function (res) {
        var filePath = res.tempFilePath;
        console.log(filePath);
        wx.openDocument({
          filePath: filePath,
          fileType: type,
          success: function (res) {
            console.log('打开文档成功')
          },
          fail: function (res) {
            console.log("1111111111111", res);
          },
          complete: function (res) {
            console.log("22222222222222", res);
          }
        })
        wx.hideLoading()
      },
      fail: function (res) {
        console.log('文件下载失败');
        wx.hideLoading()
      },
      complete: function (res) {},
    })
  },
  questionTip() { //预付无忧问号点击
    wx.showModal({
      title: '预付无忧',
      content: '平台与保险公司联合推出预付无忧保险活动。商家为店铺申请投保，在投保期限内，消费者购买该商家预付卡享时有保险服务，在投保期内因商户原因无法提供服务时，消费者可联系平台，由平台协商进行赔付事宜。',
      showCancel: false
    })
  },
  realName() { //前往实名验证
    wx.navigateTo({
      url: '../realName/realName?resultShow=2',
    })
  },
  showModalTwo() { //每个用户在同一个商户中购买承保卡数量超过5张时弹出
    var that = this
    wx.showModal({
      showCancel: false,
      title: '',
      content: '每个用户在同一个商户中购买承保卡数量为5张，很抱歉您在该商家已无法参保',
      confirmText: '我已知晓',
      confirmColor: '#FF5800',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  showModal() { //保额不足时弹窗
    var that = this
    this.data.isInsurance = '2'
    wx.showModal({
      title: '保额不足',
      content: '非常抱歉，商户剩余保额不足以承保本次支付金额，是否继续购买/充值。',
      confirmText: '继续购买',
      confirmColor: '#FF5800',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          that.wxpay()
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  noPay() { //未签署合约或未实名提示
    if (!this.data.isImg&&(Number(this.data.cardData.buyMoney) <= 500)) {
      wx.showToast({
        title: '请确认并自动签署合约',
        icon: 'none'
      })
      return
    } else if (!this.data.isImgTwo&&(Number(this.data.cardData.buyMoney) > 500)) {
      wx.showToast({
        title: '请点击我已仔细阅读',
        icon: 'none'
      })
      return
    } else if (!this.data.isContract) {
      wx.showToast({
        title: '请点击我已了解保险相关条约',
        icon: 'none'
      })
      return
    } else if (!this.data.isRealName && this.data.isInsurance == '1') {
      wx.showToast({
        title: '请完成实名验证',
        icon: 'none'
      })
      return
    }
  },
  // sumitPay(){ //点击确认支付
  //   let insured = true //保额是否充足
  //   if(!insured){
  //     this.showModal()
  //     return
  //   }else{
  //     this.wxpay()
  //   }
  // },

  //跳转签署合约(500元以上)
  signContract() {
    if (!this.data.isImgTwo) {
      wx.showToast({
        title: '请点击我已仔细阅读',
        icon: 'none'
      })
      return
    }
    wx.navigateTo({
      url: '/userPageB/pages/userStore/electronicContract/signature/signature?assetId=' + this.data.assetId + '&merchantId=' + this.data.merchantId,
    })
  },
  wxpay() { //微信支付
    console.log(this.data.isInsurance)
    if ((!this.data.isImg && (Number(this.data.cardData.buyMoney) <= 500)) || (!this.data.isImgTwo && (Number(this.data.cardData.buyMoney) > 500))) {
      wx.showToast({
        title: '请点击我已仔细阅读',
        icon: 'none'
      })
      return
    }
    var that = this
    var data = {
      assetId: this.data.assetId,
      buyerName: '',
      referrerId: this.data.referrerId,
      buyMoney: this.data.cardData.buyMoney,
      referrerPhone: '',
      staffId: this.data.staffId,
      chainMerchantId: this.data.merchantId,
      isInsurance: this.data.isInsurance,
      signUrl: this.data.signUrl,
      paySource: app.globalData.paySource,
    }
    console.log('data', data)
    WXAPI.createBuyOrder(data, (res) => {
      console.log('提交支付', res)
      if (res.code == 200) {
        var data = res.result
        wx.requestPayment({
          'timeStamp': data.timeStamp,
          'nonceStr': data.nonceStr,
          'package': data.package,
          'signType': data.signType, //MD5
          'paySign': data.paySign,
          'success': function (res) {
            console.log('支付成功', res)
            console.log(res)
            if (res.errMsg == 'requestPayment:ok') {
              wx.showToast({
                title: '支付成功',
              })
              that.setData({
                orderId: data.orderId
              })
              that.getCardPayorder()
              // setTimeout(() => {
              //   //支付页面信息
              //   wx.redirectTo({
              //     url: '/userPageB/pages/userStore/resellScuuess/resellScuuess?orderId='+data.orderId+"&pathType=cardPay",
              //   })
              // }, 1500);
            }
          },
          'fail': function (res) {
            wx.showToast({
              title: '支付失败',
              icon: 'none'
            })
            console.log('支付失败或取消支付', res)
          },
          'complete': function (res) {
            console.log('支付完成', res)
            // wx.navigateBack({})
          }
        })
      } else {
        if (res.message == '保额不足') {
          this.showModal()
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none'
          })
        }
      }
    })
  },
     //签约保险说明弹窗
  signedView(){
    this.setData({
      tipShow: true
    })
  },
  //购卡订单支付结果
  getCardPayorder() {
    const that = this
    this.setData({
      timer: setInterval(function () { //这里把setInterval赋值给变量名为timer的变量
        that.data.countdown--;
        var data = {
          orderId: that.data.orderId,
        }
        WXAPI.getBuyCardPayResult(data, (res) => {
          const data = res.result
          console.log("获取支付结果", res)
          if (data.isPay) {
            // wx.redirectTo({
            //   url: '/userPageB/pages/userStore/resellScuuess/resellScuuess?orderId=' + that.data.orderId + "&pathType=cardPay",
            // })
            wx.reLaunch({
              url: '/userPageB/pages/buyCardpuch/buyCardpuch?customerCardId=' + data.customerCardId + '&assetId=' + that.data.assetId,
            })
            clearInterval(that.data.timer);
          }
        })
        that.setData({
          countdown: that.data.countdown,
        })
        if (that.data.countdown == 0) {
          console.log("1111111111")
          clearInterval(that.data.timer);
          that.setData({
            countdown: 60,
          })
        }
      }, 1000)
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})